package org.game.manager;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.MapUtils;
import org.cfg.TaskCfg;
import org.cfg.cache.TaskCfgCache;
import org.constant.TaskConstant;
import org.game.db.bean.Player;
import org.game.db.bean.Task;
import org.game.db.cache.TaskCache;
import org.game.db.proxy.bean.PlayerDataProxy;
import org.game.module.event.handler.TaskFinishEventHandler.TaskVector;
import org.game.module.taskbo.TaskBO;
import org.game.plugin.event.GameEventPlugin;
import org.game.protobuf.s2c.S2CTaskMsg.RespTasks;
import org.game.protobuf.s2c.S2CTaskMsg.TaskInfo;
import org.game.util.ProtoUnit;

import com.google.common.collect.Lists;
import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.manager.MessageManager;
import com.xiaoleilu.hutool.date.DateUtil;

/**
 * @author : DengYing
 * @CreateDate : 2017年8月17日 下午5:32:54
 * @Description ：任务管理器
 */
public class TaskManager {
	private static TaskManager ME = new TaskManager();

	private TaskManager() {
	}

	public static TaskManager me() {
		return ME;
	}
	
	
//	/**
//	 * 检查并接取新任务
//	 * @param player
//	 */
//	public List<Task> checkAndAcceptNewTask(Player player) {
//		List<Task> addTask = Lists.newArrayList();
//		
//		List<TaskCfg> cfgs = TaskCfgCache.me().getAll();
//		
//		List<Task> tasks = player.getTasksFkPlayerId();
//		Set<Integer> taskIds = Sets.newHashSet();
//		Set<Integer> finishIds = Sets.newHashSet();
//		for (Task task : tasks) {
//			taskIds.add(task.getCid());
//			if (task.getStatus() == TaskConstant.STATUS_RECEIVE) {
//				finishIds.add(task.getCid());
//			}
//		}
//		int plv = player.getLevel();
//		for (TaskCfg taskCfg : cfgs) {
//			if (taskIds.contains(taskCfg.getId())) {
//				continue;
//			}
//			if (plv < taskCfg.getNeedPlv()) {
//				continue;
//			}
//			int needPreTaskId = taskCfg.getNeedPreTaskId();
//			if (needPreTaskId != 0 && !finishIds.contains(needPreTaskId)) {
//				continue;
//			}
//			addTask.add(acceptTask(player, taskCfg));
//		}
//		return addTask;
//	}
	

	/**
	 * 接受任务
	 * 
	 * @param player
	 * @return 
	 */
	public Task acceptTask(Player player, TaskCfg taskCfg) {
		// 进度继承
		int initProgress = taskCfg.getExtendsTaskId()!=0 ? getFinishTaskProgress(player, taskCfg.getExtendsTaskId()) : 0;
		
		Task task = new Task(0L, taskCfg.getId(), player.getId(), initProgress, TaskConstant.STATUS_RUNING,new Date());
		task.insert();
		// 初始化事件条件
		GameEventPlugin.eventConditionInit(player, new TaskVector(task), taskCfg.getFinishCondId(), taskCfg.getFinishParams(),task.getProgress(),taskCfg.getProgress());
		return task;
	}
	

	/**
	 * 通知任务更新
	 * @param player
	 * @param tasks
	 */
	public void notifyTaskInfos(Player player, List<TaskInfo> tasks) {
		if (tasks==null || tasks.isEmpty()) {
			return;
		}
		RespTasks.Builder builder = RespTasks.newBuilder();
		builder.addAllTaks(tasks);
		IMessage outMsg = MessageManager.me().create(TaskBO.getTasks, ProtoUnit.toByte(builder.build()));
		player.getPlayerProxy().sendMsg(outMsg);
	}
	
	/**
	 * 重置任务
	 * @param player
	 */
	public List<Task> resetTasks(Player player){
		List<Task> resetTasks = Lists.newArrayList();
		Date nowDate = new Date();
		List<TaskCfg> cfgs = TaskCfgCache.me().getAll();
		for (TaskCfg taskCfg : cfgs) {
			int resetType = taskCfg.getResetType();
			Task task = TaskCache.me().getByPlayerIdCid(player.getId(), taskCfg.getId());
			if (task == null || task.getStatus() == TaskConstant.STATUS_TIME_OUT) {
				continue;
			}
			Date lastResetDate = task.getLastResetDate();
			if (resetType == 2) {
				if(DateUtil.betweenDay(lastResetDate, nowDate, true)!=0){
					task.setProgress(0);
					task.setStatus(TaskConstant.STATUS_RUNING);
					task.setLastResetDate(nowDate);
					task.update();
					resetTasks.add(task);
				}
			}else {
				continue;
			}
		}
		return resetTasks;
	}
	
	/**
	 * 检查过期任务 & 删除过期任务
	 * @param player
	 */
	public List<Task> checkTimeOutTasks(Player player){
		List<Task> timeOutTasks = Lists.newArrayList();
		Date nowDate = new Date();
		List<TaskCfg> cfgs = TaskCfgCache.me().getAll();
		for (TaskCfg taskCfg : cfgs) {
			// 有效
			int effectiveTime = taskCfg.getEffectiveTime();
			Task task = TaskCache.me().getByPlayerIdCid(player.getId(), taskCfg.getId());
			if (task == null) {
				continue;
			}
			
			Date lastResetDate = task.getLastResetDate();
			if (effectiveTime != -1) {
				if(DateUtil.betweenDay(lastResetDate, nowDate, true) > effectiveTime){
					task.setStatus(TaskConstant.STATUS_TIME_OUT);
					task.delete();
					timeOutTasks.add(task);
				}
			}else {
				continue;
			}
		}
		return timeOutTasks;
	}

	public List<Task> getTaskByType(Player player,int taskType){
		List<Task> taskList = player.getTasksFkPlayerId();
		return taskList.stream()
				.filter(task->task.getTaskProxy().getTaskType() == taskType)
				.collect(Collectors.toList());
	}
	
	/**
	 * 取得已经完成的任务进度
	 * @param taskId
	 * @return
	 */
	public int getFinishTaskProgress(Player player,int taskId){
		int finishProgress = 0;
		TaskCfg cfg =TaskCfgCache.me().getById(taskId);
		if (cfg.getResetType() == TaskConstant.RESET_NO) {
			PlayerDataProxy pdProxy = player.getPlayerDatasFkPlayerId().getPlayerDataProxy();
			finishProgress = MapUtils.getIntValue(pdProxy.getFinishTasks(), taskId , 0);
		}else {
			Task task = TaskCache.me().getByPlayerIdCid(player.getId(), taskId);
			finishProgress = task == null? 0 : task.getProgress();
		}
		return finishProgress;
	}
}
